<template>
  <div class="cPage">
    <el-collapse accordion :value="0">
      <el-collapse-item
        v-for="(item, index) in pageIndexConfig"
        :key="index"
        :name="index"
      >
        <template slot="title">
          <div class="cardTop">
            <span class="text">{{ item.name }}</span>
            <el-button
              class="btn"
              @click.stop="createEditNewAd(item, false, item)"
              type="primary"
              >新增</el-button
            >
          </div>
        </template>
        <div class="content">
          <el-table :data="tableData[item.type]" border style="width: 100%">
            <template v-if="item.isPosition">
              <el-table-column prop="postion" label="广告位置">
                <template slot-scope="scope">
                  {{
                    $utils.findValueInObj(positionStatus, scope.row.position)
                  }}
                </template>
              </el-table-column>
            </template>
            <el-table-column prop="name" label="标题"> </el-table-column>
            <el-table-column label="图片" align="center">
              <template slot-scope="scope">
                <a :href="scope.row.linkUrl" target="_blank"
                  ><img class="inlineImg" :src="scope.row.coverUrl" alt=""
                /></a>
              </template>
            </el-table-column>
            <el-table-column prop="weight" label="权重" width="100">
            </el-table-column>
            <el-table-column label="可用状态" width="100">
              <template slot-scope="scope">
                <span>
                  <el-tag :type="scope.row.status ? 'success' : 'info'">{{
                    adStatus[scope.row.status]
                  }}</el-tag>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="180"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  @click="createEditNewAd(scope.row, true, item)"
                  type="text"
                  size="small"
                >
                  编辑
                </el-button>
                <el-button
                  @click="handleCurrentStatus(scope.row)"
                  type="text"
                  size="small"
                >
                  {{ scope.row.status ? "下架" : "上架" }}
                </el-button>
                <el-button
                  @click="deleteCurrentRow(scope.row)"
                  type="text"
                  size="small"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
    <el-dialog
      :title="`${isEdit ? '编辑' : '新建'}广告`"
      :visible.sync="editModalVisible"
      size="mini"
      width="600"
    >
      <el-form
        label-position="right"
        label-width="120px"
        :model="form"
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item label="广告标题" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="广告位置" prop="name">
          <el-select v-model="form.position" v-if="pageIndex.isPosition">
            <el-option
              v-for="(item, index) in positionStatus"
              :label="item.value"
              :value="item.key"
              :key="index"
              >{{ item.value }}</el-option
            >
          </el-select>
          <span v-else>{{ pageIndex.name }}</span>
        </el-form-item>
        <el-form-item label="权重" prop="weight">
          <el-input
            v-model.number="form.weight"
            style="width: 120px"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="跳转Url" prop="linkUrl">
          <el-input v-model="form.linkUrl"></el-input>
          <el-button @click="openSelectArticle = !openSelectArticle" class="addLinkBtn" type="text" size="small"
            >{{openSelectArticle ? '收起' : '添加'}} </el-button
          >
        </el-form-item>
        <div v-if="openSelectArticle" style="margin: -18px 0 18px 120px">
          <articleSelect :tabs="['ZX' , 'HD' ,'AL' ,'BG']" :selectUUID="form.sourceId" :selectArticle="selectArticle"/>
        </div>
        <el-form-item label="上线状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="(value, key) in adStatus"
              :label="Number(key)"
              :key="key"
              >{{ value }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传图片" prop="coverUrl">
          <!-- <el-upload
            style="position: relative;top: 10px;height: 120px;"
            :show-file-list="false"
            class="avatar-uploader"
            :action="uploadUrl()"
            accept="image/jpeg,image/jpg,image/png，image/webp"
            list-type="picture-card"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.coverUrl" :src="form.coverUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload> -->
          <uploadCropper :handleAvatarSuccess="handleAvatarSuccess" :url="form.coverUrl"/>
          <el-alert
            v-if="picTip"
            style="margin-top: 50px"
            show-icon
            :title="picTip"
            type="info"
          >
          </el-alert>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editModalVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { adStatus, positionStatus } from "@/config/ad";
import rules from "@/config/rules";
import articleSelect from "../../components/articleSelect";
export default {
  props: ["pageIndexConfig"],
  components: { articleSelect },
  data() {
    return {
      openSelectArticle: false,
      pageIndex: {},
      loading: false,
      picTip: "",
      tableData: {
        TOP: [],
        LB_BANNER: [],
        SMALL_BANNER: [],
      },
      // 表单相关
      editModalVisible: false,
      isEdit: false,
      form: {},
      rules,
      adStatus,
      positionStatus,
    };
  },
  methods: {
    selectArticle (item, detailName) {
      this.form.linkUrl = `https://www.iot101.com/#/${detailName}?uuid=` + item.uuid
      this.form.sourceId = item.uuid
    },
    createEditNewAd(config, isEdit, pageIndexConfig) {
      const { type, pageType, position } = config;
      const tempType = config.type;
      this.pageIndexConfig.forEach((item) => {
        if (item.type === tempType) {
          this.picTip = item.picTip;
        }
      });
      this.isEdit = isEdit;
      this.pageIndex = pageIndexConfig;
      this.form = isEdit
        ? config
        : {
            sourceId: null,
            coverUrl: "",
            status: 1,
            linkUrl: "https://www.baidu.com",
            name: "",
            weight: 1,
            type,
            position,
            pageType,
          };
      this.editModalVisible = true;
    },
    handleCurrentStatus(config) {
      this.$confirm(
        `是否确认 ${config.status ? "下架" : "上架"} 广告 [${config.name}]?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$axios
          .put(
            `/api/adverts/${config.uuid}.json?_method=put`,
            { status: Number(!config.status) }
          )
          .then((response) => {
            this.$message.success("操作成功");
            this.getAdList(config);
          });
      });
    },
    deleteCurrentRow(config) {
      this.$confirm(`是否确认删除[${config.name}]广告?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .delete(`/api/adverts/${config.uuid}.json?_method=delete`)
          .then((response) => {
            this.$message.success("操作成功");
            this.getAdList(config);
          });
      });
    },
    getAdList(config) {
      const { type, pageType, position } = config;
      const params = {
        searchKey: "",
        status: "",
        pageType,
        type,
        position,
      };
      const _this = this;
      this.$axios.get("/api/adverts.json", { params }).then((response) => {
        const tableData = JSON.parse(JSON.stringify(this.tableData));
        tableData[type] = response.list;
        _this.tableData = tableData;
      });
    },
    handleSubmit() {
      const { form, isEdit } = this;
      const ajaxType = isEdit ? "put" : "post";
      const url = isEdit
        ? `/api/adverts/${form.uuid}.json?_method=put`
        : "/api/adverts.json";
      
      if (!form.linkUrl.includes(form.sourceId)) {
        delete form.sourceId
      }
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$axios[ajaxType](url, this.form).then((response) => {
            this.$message.success("操作成功");
            this.getAdList(this.form);
            this.editModalVisible = false;
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleAvatarSuccess(res, file) {
      // debugger
      const fileObj = this.$utils.judgeLogin(res);
      this.form.coverUrl = fileObj.url;
    },
  },
  created() {
    this.pageIndexConfig.forEach((item) => {
      this.getAdList(item);
    });
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
.addLinkBtn {
  margin-top: 10px;
}
</style>
